import java.util.Arrays;
import java.util.Scanner;

public class 费解的开关 {
    static int N = 5;
    static int[][] bak = new int[5][5];
    static int[][] arr = new int[5][5];
    static int[] dx = {-1,0,1,0,0};
    static int[] dy = {0,0,0,-1,1};

    public static void main(String[] args) {
        int n = 0;
        Scanner s = new Scanner(System.in);
        n = s.nextInt();
        while(n!=0) {
            s.nextLine();
            n--;
            int min = 6;
            //
            for(int i=0;i<5;i++) {
                String line = s.nextLine();
                for(int j=0;j<5;j++) {
                    bak[i][j] = line.charAt(j)-'0';
                }
            }

            //枚举第一行
            for(int k=0; k<32;k++) {
                int count = 0;
                CopyArray();
                for(int i=0;i<5;i++)
                    if((k>>i&1) == 1) {
                        count++;
                        turn(0,i);
                    }

                //后面的在操作看前一行
                for(int i=0;i<4;i++)
                    for(int j=0;j<5;j++) {
                        if(bak[i][j]==0) {
                            count++;
                            turn(i+1,j);
                        }
                    }

                //
                boolean dack = true;//最后一行全亮
                for(int i=0;i<5;i++) {
                    if(bak[4][i]==0) {
                        dack = false;
                        break;
                    }
                }

                if(dack) {
                    min = count>min?min:count;
                    System.out.println("min:"+min+"|"+"count"+count);
                }

            }
            if(min>6) System.out.println(-1);
            else System.out.println(min);


        }
    }
    //拷贝数组
    private static void CopyArray() {
        for(int i=0;i<5;i++) {
            for(int j=0;j<5;j++) {
                arr[i][j] = bak[i][j];
            }
        }
    }
    //按下一个灯，发生的变化
    private static void turn(int x,int y) {
        for(int i=0;i<5;i++) {
            int a = x+dx[i];
            int b = y+dy[i];
            if(a>=0 && a<5 && b>=0 && b<5)
                bak[a][b]^=1;
        }
    }
}
